<script setup>

import {isPermission} from "../../../utils/utils.js";
import {ArrowLeftBold, ArrowRightBold, Check, Location, VideoPlay} from "@element-plus/icons-vue";
import {ref} from "vue";
import router from "../../../router/index.js";
import {
  getChapterTestQuestionOptions, getFinishList,
  getOneCourseSonChapter, getStudentChapterAnswer, isSubmitChapterTest,
  listChapterTestQuestions,
  listCourseChapter,
  listCourseSonChapter, submitChapter, submitChapterAnswer
} from "../../../api/course/course.js";
import {VideoPlayer} from "@videojs-player/vue";
import DoAnswer from "./DoAnswer.vue";
import {ElMessage} from "element-plus";

let playerOptions = ref({
  // height: 200,
  // width: document.documentElement.clientWidth, //播放器宽度
  playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
  autoplay: 'any', // 如果true,浏览器准备好时开始回放。
  muted: true, // 默认情况下将会消除任何音频。
  loop: true, // 导致视频一结束就重新开始。
  preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
  language: 'zh-CN',
  aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
  fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
  notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
  controls: true,
  controlBar: {
    timeDivider: true,
    durationDisplay: true,
    remainingTimeDisplay: false,
    fullscreenToggle: true // 全屏按钮
  }
})

// 题型数组
const type = ref(['单选题', '多选题', '判断题', '填空题', '问答题'])
// 题目数组
const practices = ref([])
// 总题目数
const total = ref(10)
// 单个题目
const question = ref({})
// 作业题目数组(解析个屁,顺序查询)
const chapterTestQuestions = ref([])
// 是否提交过
const isSubmit = ref()
// 当前题目索引
const questionIndex=ref(0);
// 正确答案数组
const rightAnswer = ref([])
// 单选选项
const radioOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}]);
//多选选项
const checkboxOptions = ref([{
  value: 'A',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'B',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'C',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'D',
  content: '',
  checked: 0
}])
// 判断题选项
const judgeOptions = ref([{
  value: 'T',
  content: '',
  checked: 0 // 选项未选中状态
}, {
  value: 'F',
  content: '',
  checked: 0 // 选项未选中状态
}])

// 选项对象
const option = ref({
  practiceId: 0,
  a: '',
  b: '',
  c: '',
  d: ''
})
//
const activeIndex = ref();
// 获取当前章节id
const sonChapterId = ref();
sonChapterId.value = router.currentRoute.value.params.id;
// 当前章节信息
const sonChapter = ref({})
// 视频播放还是章节检测
const isVideoOrTest = ref(0);
// 完成章节的名单
const finishList = ref()
// 课程id
const courseId = ref('');
courseId.value = localStorage.getItem('courseId');
// 大章节
const courseChapters = ref([])
// 小章节
const courseSonChapters = ref([])
// 跳转到小章节页面
const handleGoSonChapterOne = (courseChapterId, courseSonChapterId) => {
  console.log(activeIndex.value);
  activeIndex.value = courseChapterId + '-' + courseSonChapterId;
  sonChapterId.value = courseSonChapterId;
  handleOneCourseSonChapter();
}

// 查看大章节
const handleCourseChapter = async () => {
  await listCourseChapter(courseId.value).then(res => {
    courseChapters.value = res.data;
    console.log(courseChapters.value);
  })
  for (let i = 0; i < courseChapters.value.length; i++) {
    // console.log(courseChapters.value[i].id);
    await handleCourseSonChapter(courseChapters.value[i].id);
  }
}

// 小章节
const handleCourseSonChapter = async (chapterId) => {
  // console.log(chapterId);
  await listCourseSonChapter(chapterId).then(res => {
    courseSonChapters.value.push(res.data);
  })
  console.log(courseSonChapters.value);
}
// 查看当前章节信息
const handleOneCourseSonChapter = async () => {
  await getOneCourseSonChapter(sonChapterId.value).then(res => {
    sonChapter.value = res.data;
    console.log(sonChapter.value);
  })
}


// 判断是否是选择
const isOption = () => {
  if (question.value.type === 0) {
    // console.log("单选");
    option.value.a = radioOptions.value[0].content;
    option.value.b = radioOptions.value[1].content;
    option.value.c = radioOptions.value[2].content;
    option.value.d = radioOptions.value[3].content;
    return true;
  } else if (question.value.type === 1) {
    // console.log("多选");
    option.value.a = checkboxOptions.value[0].content;
    option.value.b = checkboxOptions.value[1].content;
    option.value.c = checkboxOptions.value[2].content;
    option.value.d = checkboxOptions.value[3].content;
    return true;
  } else if (question.value.type === 2) {
    // console.log("判断");
    option.value.a = judgeOptions.value[0].content;
    option.value.b = judgeOptions.value[1].content;
    return true;
  } else return false;
}

// 选项赋值
const assignOption = () => {
  if (question.value.type === 0) {
    radioOptions.value[0].content = option.value.a;
    radioOptions.value[1].content = option.value.b;
    radioOptions.value[2].content = option.value.c;
    radioOptions.value[3].content = option.value.d;
  } else if (question.value.type === 1) {
    checkboxOptions.value[0].content = option.value.a;
    checkboxOptions.value[1].content = option.value.b;
    checkboxOptions.value[2].content = option.value.c;
    checkboxOptions.value[3].content = option.value.d;
  } else if (question.value.type === 2) {
    judgeOptions.value[0].content = option.value.a;
    judgeOptions.value[1].content = option.value.b;
  }
}


// 获取题目选项
const handleGetQuestionOptions = async () => {
  console.log(question.value);
  await getChapterTestQuestionOptions(question.value.id).then(res => {
    option.value = res.data;
    // 给选项赋值
    assignOption();
  })
}
// 获取当前作业所有题目
const handleListChapterTestQuestions = async () => {
  isVideoOrTest.value=1
  await listChapterTestQuestions(sonChapterId.value).then(res => {
    chapterTestQuestions.value = res.data;
    handleIsSubmitChapterTest().then(res => {
      if(!isSubmit.value){
        chapterTestQuestions.value.map(question => question.answer = []);
      }
      else{
        rightAnswer.value= chapterTestQuestions.value.map(question => question.answer);
        chapterTestQuestions.value.map(question => question.answer = []);
        handleGetStudentChapterAnswer()
      }
      handleIsFinishChapter();
    })
    console.log(chapterTestQuestions.value);
    //   获取第一个题目
    question.value = chapterTestQuestions.value[0];
    if (isOption())
      handleGetQuestionOptions();
    //   解析题目数组为跳转卡片
    handleChapterTestQuestionsToPractices();
  })
}

// 解析题目数组
const handleChapterTestQuestionsToPractices = () => {
  for (let i = 0; i < chapterTestQuestions.value.length; i++) {
    if (!practices.value.map(practice => practice.type).includes(chapterTestQuestions.value[i].type)) {
      practices.value.push({
        type: chapterTestQuestions.value[i].type,
        content: [chapterTestQuestions.value[i]]
      })
      // console.log(practices.value);
    } else {
      // console.log(practices.value.map(practice=>practice.type).indexOf(item));
      // 获取题目内容
      practices.value[practices.value.map(practice => practice.type).indexOf(chapterTestQuestions.value[i].type)].content.push(chapterTestQuestions.value[i]);
    }
  }// console.log(practices.value)
}
// 跳转上一题
const handleLeftQuestion = () => {
  question.value=chapterTestQuestions.value[questionIndex.value-1];
  questionIndex.value--;
  handleGetQuestionOptions()
}
// 跳转下一题
const handleRightQuestion = () => {
  question.value=chapterTestQuestions.value[questionIndex.value+1];
  questionIndex.value++;
  handleGetQuestionOptions()
}

// 提交答案
const handleSubmitAnswer=async ()=>{
  await submitChapter(sonChapterId.value).then(res=> {
    const studentChapterId = res.data;
    const studentAnswer = practices.value.flatMap(practice => practice.content.map(
        question => {
          if (Array.isArray(question.answer) && question.answer.length === 0) {
            return null; // 或者直接返回 undefined
          }
          return {
            answer: typeof question.answer === 'object' && question.answer instanceof Array ? '' : question.answer,
            studentTestId: studentChapterId,
            testQuestionId: question.id
          };
        }
    ).filter(Boolean)); // 使用 filter(Boolean) 来过滤掉 null 或 undefined 的元素
    submitChapterAnswer(studentAnswer).then(res=>{
      ElMessage.success("提交成功");
      handleListChapterTestQuestions();

    })
  })
}
// 查询学生是否已经提交过章节检测
const handleIsSubmitChapterTest=async ()=>{
  await isSubmitChapterTest(sonChapterId.value).then(res=>{
    isSubmit.value=res.data;
  })
}
// 获取学生章节检测答案
const handleGetStudentChapterAnswer=async ()=>{
  await getStudentChapterAnswer(isSubmit.value.id).then(res=>{
    chapterTestQuestions.value = chapterTestQuestions.value.map((question, index) => {
      const matchingItem = res.data.find(item => item.testQuestionId === question.id);
      if (matchingItem) {
        question.answer = matchingItem.answer;
      }
      return question;
    });
    console.log(chapterTestQuestions.value);
  })
}
// 获取章节是否已经完成
const handleIsFinishChapter=async ()=>{
  await getFinishList(courseId.value).then(res=>{
    finishList.value=res.data;
    console.log(finishList.value);
    courseSonChapters.value = courseSonChapters.value.map((subArray) => {
      return subArray.map((chapter) => {
        const finish = finishList.value.find(item => item.chapterId === chapter.id);
        if (finish) {
          chapter.status = '1'; // 已完成
        }
        return chapter;
      });
    });
    console.log(courseSonChapters.value)
  })
}



// 跳转编辑页面
const handleGoChapterMange=()=>{
  router.push("/chaptermanage")
}
// 跳转返回页面
const handleBack=()=>{
  router.push("/course/chapter");
}

handleCourseChapter();
handleOneCourseSonChapter();
</script>

<template>
  <div class="common-layout">
    <el-container>
      <!--      没啥鸟用的东西-->
      <el-header style="background: #3a4357;height: 10vh">
        <div style="display: flex; align-items: center; height: 100%;">
          <el-button type="primary" style="width: 100px"  @click="handleBack()">返回</el-button>
          <span style="margin-left: 50%;color: white">章节详情</span>
          <el-button type="primary" style="margin-left: auto" v-if="isPermission(2)" @click="handleGoChapterMange">编辑章节</el-button>

        </div>
      </el-header>
      <el-container>
        <!--        主体-->
        <el-main style="height: 90vh;margin-left: 45px">
          <h2>{{ sonChapter.name }}</h2>
          <div style="display: flex; align-items: center;justify-content: left;margin-bottom: 10px">
            <el-button style="border-radius: 14px;" :class="{'video-test': isVideoOrTest===0}" @click="isVideoOrTest=0">1视频</el-button>
            <el-button style="border-radius: 14px;" :class="{'video-test': isVideoOrTest===1}" @click="handleListChapterTestQuestions">2章节检测</el-button>
          </div>
          <!--          视频-->
          <video-player
              :src="sonChapter.videoLink"
              :options="playerOptions"
              :volume="0.6"
              v-if="isVideoOrTest===0"
          />
          <!--          章节检测-->
            <div style="display: flex;justify-content: space-between;position: relative" v-if="isVideoOrTest===1">
              <el-icon size="30" style="margin-top: 42vh" @click="handleLeftQuestion()" v-if="questionIndex!==0">
                <ArrowLeftBold/>
              </el-icon>
              <el-icon size="30" v-if="questionIndex===0"></el-icon>
              <!--          题型-->
              <div>
                <h3>{{ type[question.type] }}</h3>
                <!--          题目-->
                <div style="height: 60vh;display: flex">
                  <el-form
                      :label-position="'top'"
                      label-width="auto"
                      :model="question"
                      style="max-width: 900px"
                  >
                    <el-form-item label="题目内容">
                      <div>{{ question.content }}</div>
                    </el-form-item>
                    <!--        题目类型选择-->
                    <DoAnswer :practice="question" :radioOptions="radioOptions" :judge-options="judgeOptions"
                              :checkbox-options="checkboxOptions"></DoAnswer>
                  </el-form>
                </div>
                <div v-if="isSubmit">正确答案:{{rightAnswer[questionIndex]}}</div>
              </div>
              <el-icon size="30" style="margin-top: 42vh" v-if="questionIndex!==chapterTestQuestions.length-1" @click="handleRightQuestion()">
                <ArrowRightBold/>
              </el-icon>
              <el-icon size="30" v-if="questionIndex===chapterTestQuestions.length-1"></el-icon>
              <div class="button-div">
<!--                <el-button>取消</el-button>-->
                <el-button type="primary" style="width: 100px" @click="handleSubmitAnswer()" v-if="questionIndex===chapterTestQuestions.length-1&&!isSubmit">提交</el-button>
              </div>
            </div>
        </el-main>
        <el-divider direction="vertical" style="height: 90vh"/>
        <!--        章节跳转区-->
        <el-aside width="400px" style="height: 90vh;">
          <h4>目录</h4>
          <el-menu
              :default-active="activeIndex"
              class="el-menu-vertical-demo"
              v-for="(courseChapter,index) in courseChapters"
              :key="courseChapter.id"
              :default-openeds="[courseChapter.id]"
          >
            <el-sub-menu :index="courseChapter.id">
              <!--              大章节名称-->
              <template #title>
                <el-icon>
                  <location/>
                </el-icon>
                <span>{{ courseChapter.name }}</span>
              </template>
              <!--              大章节下的小章节-->
              <el-menu-item
                  :index="courseChapter.id+'-'+courseSonChapter.id"
                  @click="handleGoSonChapterOne(courseChapter.id,courseSonChapter.id)"
                  v-for="courseSonChapter in courseSonChapters[index]"
                  :key="courseSonChapter.id"
              >
                <div style="display: flex; align-items: center;">
                  <!--                    完成章节时-->
                  <el-icon class="finish-icon" v-if="courseSonChapter.status == '1'">
                    <Check color="#ffffff"/>
                  </el-icon>
                  <!--                    未完成章节时-->
                  <div class="no-finish-icon" v-if="courseSonChapter.status == '0'">
                    <span style="color: #FFFFFF;margin-left: 8px">1</span>
                  </div>
                  <!--              小章节的名称-->
                  <span>{{ courseSonChapter.name }}</span>
                </div>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>

      </el-container>
    </el-container>
  </div>
</template>

<style scoped lang="less">
.finish-icon {
  background: #52cc5c;
  border-radius: 100px;
  height: 24px;
  width: 20px;
  margin-right: 10px
}

.no-finish-icon {
  background: #ffb04e;
  //圆角
  border-radius: 14px;
  height: 25px;
  width: 25px;
  margin-right: 10px;
  display: flex;
  align-items: center;
}

.video-test{
  background-color: #409eff;
  color: white
}

.button-div {
  position: absolute;
  bottom: 0;
  left: 50%;
}

</style>